import numpy as np
from tensorflow.keras import backend as K

def ctc_decode_tail_blank(r):
    # r是一个np.ndarray
    res=[]
    for i in range(len(r)):
        p=0
        while p<len(r[i]) and r[i][p]!=-1:
            p+=1
        res.append(r[i][:p])
    return res

def ctc_decode_and_remove_tail(y):
    in_len=np.ones((len(y)),dtype=np.int32)*y.shape[1]
    r=K.ctc_decode(y,in_len,greedy=True,beam_width=100,top_paths=1)
    r=r[0][0].numpy()
    encoded_phonemes=ctc_decode_tail_blank(r)
    return encoded_phonemes